package com.yyx.app1.tool;

/**
 * Created by yuexing on 2015/11/9.
 */
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.yyx.app1.Data.BaseDataManager;
import com.yyx.app1.Data.DataInit;
import com.yyx.app1.Interface.Trancaction;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by Acker on 2014/12/18.
 */

public class JsonObjectPostRequest extends Request<JSONObject> {
    private Map<String, String> mMap;
    private Response.Listener<JSONObject> mListener;
    public String cookieFromResponse;
    private String mHeader;
    private Map<String, String> sendHeader=new HashMap<String, String>(1);
    public JsonObjectPostRequest(String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, Map map) {
        super(Request.Method.POST, url, errorListener);
        mListener = listener;
        mMap = map;
    }

    //当http请求是post时，则需要该使用该函数设置往里面添加的键值对
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return mMap;
    }
    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        JSONObject jsonObject = null;
        try {
            String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            jsonObject = new JSONObject(jsonString);
            mHeader = response.headers.toString();
            Map<String,String> hashMap = response.headers;
            Log.w("LOG","get headers in parseNetworkResponse "+response.headers.toString());
            //使用正则表达式从reponse的头中提取cookie内容的子串
            // 将cookie字符串添加到jsonObject中，该jsonObject会被deliverResponse递交，调用请求时则能在onResponse中得到
            String setcookie = hashMap.get("Set-Cookie");
            if (setcookie.isEmpty() || setcookie == null)
            {
                Log.i("正常", "收Set-Cookie=空"+setcookie);
                jsonObject.put("Set-Cookie", null);
            }
            else
            {
                jsonObject.put("Set-Cookie",setcookie);
            }
        }
        catch (Exception e)
        {
            Log.e("异常1511091749","可忽略"+e.toString());
        }
        return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        mListener.onResponse(response);
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return sendHeader;
    }
    public void setSendCookie(String cookie){
        sendHeader.put("Cookie",cookie);
    }

    public static void HttpPost(final Context context,HashMap<String, String> mMap,String function, final Trancaction trancaction)
    {
        String URL = DataInit.httpHead+function+".action";
        Log.i("正常",URL);
        JsonObjectPostRequest jsonObjectPostRequest = new JsonObjectPostRequest(URL, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                //从服务器响应response中的jsonObject中取出cookie的值，存到本地sharePreference
                String cookie = null;
                try {
                    cookie = jsonObject.getString("Set-Cookie");
                } catch (Exception e) {
                }
                if (cookie == null || cookie.isEmpty())
                {
                    MySharedPreferences.findAll(context);
                }
                else {
                    MySharedPreferences.put(context, "Set-Cookie", cookie);
                }
                trancaction.onResponse(jsonObject);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context, "网络错误，登录失败！", Toast.LENGTH_SHORT).show();
                trancaction.onErrorResponse(volleyError);
            }
        }, mMap){
            @Override
            public Priority getPriority() {
                return trancaction.getPriority();
            }
        };
        try {
            String localCookieStr = MySharedPreferences.get(context,"Set-Cookie");
            if(localCookieStr.isEmpty() || localCookieStr == null){
                Log.e("异常1511091208", "读本地Cookie空");
            }
            jsonObjectPostRequest.setSendCookie(localCookieStr);//向服务器发起post请求时加上cookie字段
        }
        catch (Exception e)
        {
            Log.e("异常1511091246","可忽略"+e.toString());
        }
        BaseDataManager.getMyRequestQueue(context).add(jsonObjectPostRequest);
    }
}